Page({
  data: {
    animationData: {},
    isRotating: false,
    points: 0,
    prizes: [
      { id: 1, name: '88积分', probability: 25, type: 'points', value: 88, color: '#FFF4D6' },
      { id: 2, name: '谢谢参与', probability: 20, type: 'none', value: 0, color: '#FFE4E1' },
      { id: 3, name: '66积分', probability: 25, type: 'points', value: 66, color: '#FFF4D6' },
      { id: 4, name: '1积分', probability: 20, type: 'points', value: 1, color: '#FFE4E1' },
      { id: 5, name: '288积分', probability: 10, type: 'points', value: 288, color: '#FFF4D6' },
      { id: 6, name: '2积分', probability: 10, type: 'points', value: 2, color: '#FFE4E1' },
      { id: 7, name: '88积分', probability: 10, type: 'points', value: 88, color: '#FFF4D6' },
      { id: 8, name: '5积分', probability: 20, type: 'points', value: 5, color: '#FFE4E1' }
    ],
    costPoints: 5, // 每次抽奖消耗的积分
  },

  onLoad() {
    this.fetchUserPoints();
  },

  // 获取用户积分
  fetchUserPoints() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    wx.request({
      url: 'https://www.haoyuming.online/api/user/point',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            points: res.data.data.points
          });
        }
      },
      fail: (err) => {
        if (err.statusCode === 401) {
          wx.clearStorageSync();
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  },

  // 开始抽奖
  startLottery() {
    if (this.data.isRotating) {
      return;
    }

    if (this.data.points < this.data.costPoints) {
      wx.showToast({
        title: '积分不足',
        icon: 'none'
      });
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }

    // 扣除积分
    wx.request({
      url: 'https://www.haoyuming.online/api/user/point/deduct',
      method: 'POST',
      header: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      },
      data: {
        points: this.data.costPoints,
        source: '抽奖消耗'
      },
      success: (res) => {
        if (res.data.code === 200) {
          this.setData({
            points: this.data.points - this.data.costPoints
          });
          this.rotateWheel();
        } else {
          wx.showToast({
            title: res.data.message || '扣除积分失败',
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        if (err.statusCode === 401) {
          wx.clearStorageSync();
          wx.showToast({
            title: '登录已过期，请重新登录',
            icon: 'none'
          });
          wx.navigateTo({
            url: '/pages/login/login'
          });
        }
      }
    });
  },

  // 转盘旋转动画
  rotateWheel() {
    this.setData({ isRotating: true });

    // 先重置动画状态
    const resetAnimation = wx.createAnimation({
      duration: 0,
      timingFunction: 'step-start'
    });
    resetAnimation.rotate(0).step();
    this.setData({
      animationData: resetAnimation.export()
    });

    // 延迟一帧后开始新的动画
    setTimeout(() => {
      // 随机选择奖品
      const prize = this.getRandomPrize();
      const baseRotate = 1800; // 基础旋转圈数（5圈）
      const singleAngle = 360 / this.data.prizes.length; // 每个奖品占的角度
      const halfAngle = singleAngle / 2; // 每个奖品角度的一半
      // 计算最终角度：基础圈数 + (奖品索引 * 单个奖品角度) + 偏移校准
      const angle = (prize.index * singleAngle) + halfAngle;
      const finalRotate = baseRotate - angle;

      const animation = wx.createAnimation({
        duration: 4000,
        timingFunction: 'ease-out'
      });

      animation.rotate(finalRotate).step();
      this.setData({
        animationData: animation.export()
      });

      // 动画结束后处理
      setTimeout(() => {
        this.setData({ isRotating: false });
        this.handlePrize(prize.item);
      }, 4000);
    }, 50);
  },

  // 根据概率随机获取奖品
  getRandomPrize() {
    const total = this.data.prizes.reduce((sum, prize) => sum + prize.probability, 0);
    let random = Math.random() * total;
    
    for (let i = 0; i < this.data.prizes.length; i++) {
      const prize = this.data.prizes[i];
      if (random <= prize.probability) {
        return { item: prize, index: i };
      }
      random -= prize.probability;
    }
    
    return { item: this.data.prizes[1], index: 1 }; // 默认返回"谢谢参与"
  },

  // 处理中奖结果
  handlePrize(prize) {
    if (prize.type === 'points' && prize.value > 0) {
      // 增加积分
      const token = wx.getStorageSync('token');
      wx.request({
        url: 'https://www.haoyuming.online/api/user/points/add',
        method: 'POST',
        header: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json'
        },
        data: {
          points: prize.value,
          source: '抽奖获得'
        },
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({
              points: this.data.points + prize.value
            });
            wx.showModal({
              title: '恭喜中奖',
              content: `获得 ${prize.value} 积分`,
              showCancel: false
            });
          }
        },
        fail: (err) => {
          if (err.statusCode === 401) {
            wx.clearStorageSync();
            wx.showToast({
              title: '登录已过期，请重新登录',
              icon: 'none'
            });
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
    } else {
      wx.showModal({
        title: '很遗憾',
        content: '谢谢参与，下次再来',
        showCancel: false
      });
    }
  },

  // 返回上一页
  onBackTap() {
    wx.navigateBack();
  }
}); 